/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "MeshObject.h"
#include "SceneObject.h"

#include "OgreSkeletonManager.h"

namespace PQEngine
{
	MeshObject::MeshObject(SceneObject* sceneObject,Ogre::String meshName)
		: GameObject(sceneObject,GAME_OBJECT_MESH),_entity(0)
	{
		assert(sceneObject);

		_entity=sceneObject->getSceneManager()->createEntity(meshName);
		_mesh=_entity->getMesh();
		_meshName=_mesh->getName();
		_meshGroup=_mesh->getGroup();
		
		//NOTE: when we attach mesh component ,
		//we do attach entity to the game scene node.
		_component=new MeshComponent(this);
		_component->attach(this);

		//So here is wrong
		//_sceneNode->attachObject(_entity);
	}

	Ogre::Entity* MeshObject::getEntity()
	{
		return _entity;
	}

	void MeshObject::addSkeletonAnim(Ogre::String &name)
	{
		Ogre::SkeletonPtr skel=Ogre::SkeletonManager::getSingleton().load(name,_meshGroup);

		Ogre::SkeletonInstance *skeleton = _entity->getSkeleton();
		skeleton->addLinkedSkeletonAnimationSource(name);
		_entity->refreshAvailableAnimationState();

		/*
		int num=skel->getNumAnimations();

		Ogre::AnimationStateSet* anims= _entity->getAllAnimationStates();
		for(int i=0;i<num;++i){
			Ogre::Animation* anim= skel->getAnimation(i);
			Ogre::String name= anim->getName();
			Ogre::Real len=anim->getLength();
			Ogre::AnimationState *state= anims->createAnimationState(name,0,len);
			Ogre::SkeletonInstance *skeleton = _entity->getSkeleton();
		}
		*/
		_component->reset();

	}

	void MeshObject::rotate( const Ogre::Vector3& axis, const Ogre::Radian& angle, Ogre::Node::TransformSpace relativeTo /*= Ogre::Node::TS_LOCAL*/ )
	{
		if(_sceneNode){
			_sceneNode->rotate(axis,angle,relativeTo);
		}
	}

	void MeshObject::scale( const Ogre::Vector3& scale )
	{
		if(_sceneNode){
			_sceneNode->scale(scale);
		}

	}

	void MeshObject::setBlendMode( Ogre::SkeletonAnimationBlendMode state )
	{
		_entity->getSkeleton()->setBlendMode(state);
	}

	
}
